package com.chujian.framework.util.mybatis.wrapper;

import com.chujian.framework.core.tsdata.TsDataConst;
import com.chujian.framework.util.DateUs;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.Temporal;

public class OperateBetweenWrapperBuilder implements IOperateWrapperBuilder {

    @Override
    public boolean build(WrapperUnit unit) {
        if (TsDataConst.QUERY_BETWEEN_SUFFIX_RANGE.equals(unit.operate)) {
            Object[] values = toRangeVal(unit.field.getType(), unit.value.toString());
            unit.wrapper.between(unit.col, values[0], values[1]);
            return true;
        }
        return false;
    }

    public static Object[] toRangeVal(Class<?> fieldType, String value) {
        String[] parts = value.split(",");

        // 时间系列
        if (Temporal.class.isAssignableFrom(fieldType)) {
            if (LocalDateTime.class.equals(fieldType)) {
                return new LocalDateTime[]{DateUs.toLocalDateTime(parts[0]), DateUs.toLocalDateTime(parts[1])};

            } else if (LocalDate.class.equals(fieldType)) {
                return new LocalDate[]{DateUs.toLocalDate(parts[0]), DateUs.toLocalDate(parts[1])};

            } else if (LocalTime.class.equals(fieldType)) {
                return new LocalTime[]{DateUs.toLocalTime(parts[0]), DateUs.toLocalTime(parts[1])};

            }
        }
        return parts;

    }
}
